package com.kingviker.example.zerocopy;

import sun.nio.ch.SelChImpl;

import javax.sound.midi.Soundbank;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(true);
        socketChannel.connect(new InetSocketAddress("localhost", 8899));
        System.out.println(socketChannel instanceof SelChImpl);
        String fileName = "d:/1.rar";
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        long startTime = System.currentTimeMillis();
        System.out.println("文件大小:" + fileChannel.size());
        long transferedCount = 0;
        //transferTo 每次传输的大小受到不同的操作系统的限制,Windows10下测试的 并且查到了源码,每次只能传输8m,
        // 所以要循环调用,并判断transferto返回的传输字节大小判断是否整个文件传输完毕
        while (transferedCount < fileChannel.size()) {
            long transferCount = fileChannel.transferTo(transferedCount, fileChannel.size(), socketChannel);
            transferedCount += transferCount;
//            System.out.println("发送总字节数:"+transferedCount+",耗时:"+(System.currentTimeMillis()-startTime));
        }

        System.out.println("发送总字节数:" + transferedCount + ",耗时:" + (System.currentTimeMillis() - startTime));
        socketChannel.close();
        fileChannel.close();
    }
}
